package com.yuanrui.subject.domain.service.impl;

import com.yuanrui.subject.common.entity.PageResult;
import com.yuanrui.subject.common.enums.IsDeletedFlagEnum;
import com.yuanrui.subject.common.redis.RedisUtil;
import com.yuanrui.subject.common.util.IdWorkerUtil;
import com.yuanrui.subject.common.util.LoginUtil;
import com.yuanrui.subject.domain.convert.SubjectInfoConvert;
import com.yuanrui.subject.domain.entity.SubjectInfoBO;
import com.yuanrui.subject.domain.entity.SubjectOptionBO;
import com.yuanrui.subject.domain.handler.subject.SubjectTypeHandlerFactory;
import com.yuanrui.subject.domain.service.SubjectInfoDomainService;
import com.yuanrui.subject.domain.service.SubjectLikedDomainService;
import com.yuanrui.subject.infra.basic.entity.SubjectInfo;
import com.yuanrui.subject.infra.basic.entity.SubjectInfoEs;
import com.yuanrui.subject.infra.basic.entity.SubjectLabel;
import com.yuanrui.subject.infra.basic.entity.SubjectMapping;
import com.yuanrui.subject.infra.basic.service.*;
import com.yuanrui.subject.infra.entity.UserInfo;
import com.yuanrui.subject.infra.rpc.UserRpc;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;


@Service
@Slf4j
public class SubjectInfoDomainServiceImpl implements SubjectInfoDomainService {

    @Resource
    private SubjectInfoService subjectInfoService;
    @Resource
    private SubjectTypeHandlerFactory subjectTypeHandlerFactory;

    @Resource
    private SubjectMappingService subjectMappingService;

    @Resource
    private SubjectLabelService subjectLabelService;
    @Resource
    private SubjectEsService subjectEsService;

    @Resource
    private UserRpc userRpc;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private SubjectLikedDomainService subjectLikedDomainService;

    private static final String RANK_KEY = "subject:rank";

    @Override
    @Transactional
    public void add(SubjectInfoBO subjectInfoBO) {
        //如果将题目添加全部写在主流程中，那么主流程会变得非常复杂，不利于维护
        //判断type 1.选择题 2.判断题 3.填空题 4.问答题
        //if结构会变得非常复杂
        //使用工厂策略模式，将不同的题目类型的添加逻辑分离出去
        //一个工厂包含了所有的题目类型，根据传入的type，返回对应的工厂
        SubjectInfo subjectInfo = SubjectInfoConvert.INSTANCE.convertToInfoEntity(subjectInfoBO);
        //保存题目信息
        subjectInfo.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        subjectInfoService.insert(subjectInfo);
        //根据题目类型，调用对应的处理器，保存题目答案选项信息
        subjectInfoBO.setId(subjectInfo.getId());
        subjectTypeHandlerFactory.getHandler(subjectInfoBO.getSubjectType()).add(subjectInfoBO);
        //保存题目分类信息与标签信息的关联
        List<Integer> categoryIds = subjectInfoBO.getCategoryIds();
        List<Integer> labelIds = subjectInfoBO.getLabelIds();
        List<SubjectMapping> subjectMappings = new LinkedList<>();
        //多对多关联关系
        categoryIds.forEach(categoryId -> {
            labelIds.forEach(labelId -> {
                SubjectMapping subjectMapping = new SubjectMapping();
                subjectMapping.setSubjectId(subjectInfo.getId());
                subjectMapping.setCategoryId(Long.valueOf(categoryId));
                subjectMapping.setLabelId(Long.valueOf(labelId));
                subjectMapping.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
                subjectMappings.add(subjectMapping);
            });
        });
        subjectMappingService.batchInsert(subjectMappings);

        //同步es
        SubjectInfoEs subjectInfoEs = new SubjectInfoEs();
        subjectInfoEs.setSubjectId(subjectInfo.getId());
        subjectInfoEs.setDocId(new IdWorkerUtil(1, 1, 1).nextId());
        subjectInfoEs.setSubjectName(subjectInfo.getSubjectName());
        subjectInfoEs.setSubjectAnswer(subjectInfoBO.getSubjectAnswer());
        subjectInfoEs.setCreatedUser(LoginUtil.getLoginId());
        subjectInfoEs.setCreatedTime(new Date().getTime());
        subjectInfoEs.setSubjectType(subjectInfo.getSubjectType());
        subjectEsService.insert(subjectInfoEs);
        //redis放入zset 计入贡献榜
        redisUtil.addScore(RANK_KEY, LoginUtil.getLoginId(), 1);
    }

    /**
     * 分页查询题目信息
     *
     * @param subjectInfoBO 查询条件
     * @return 分页结果
     */
    @Override
    public PageResult<SubjectInfoBO> getSubjectPage(SubjectInfoBO subjectInfoBO) {
        PageResult<SubjectInfoBO> pageResult = new PageResult<>();
        pageResult.setPageNo(subjectInfoBO.getPageNo());
        pageResult.setPageSize(subjectInfoBO.getPageSize());
        int start = (subjectInfoBO.getPageNo() - 1) * subjectInfoBO.getPageSize();
        SubjectInfo subjectInfo = SubjectInfoConvert.INSTANCE.convertToInfoEntity(subjectInfoBO);
        int count = subjectInfoService.countByCondition(subjectInfo, subjectInfoBO.getCategoryId(), subjectInfoBO.getLabelId());
        if (count == 0) {
            return pageResult;
        }
        List<SubjectInfo> subjectInfoList = subjectInfoService.queryPage(subjectInfo, subjectInfoBO.getCategoryId(), subjectInfoBO.getLabelId(), start, subjectInfoBO.getPageSize());
        List<SubjectInfoBO> subjectInfoBOS = SubjectInfoConvert.INSTANCE.convertToInfoBoList(subjectInfoList);
        subjectInfoBOS.forEach(subjectInfoBo -> {
            List<String> labelNameList = new ArrayList<>();
            SubjectMapping subjectMapping = new SubjectMapping();
            subjectMapping.setSubjectId(subjectInfoBo.getId());
            subjectMapping.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
            //获取标签信息
            List<SubjectMapping> mappings = subjectMappingService.queryLabelByCategoryId(subjectMapping);
            List<Long> labelIds = mappings.stream().map(SubjectMapping::getLabelId).toList();
            List<SubjectLabel> labelList = subjectLabelService.batchQueryById(labelIds);
            labelList.stream().map(SubjectLabel::getLabelName).forEach(labelNameList::add);
            subjectInfoBo.setLabelName(labelNameList);
        });
        pageResult.setResult(subjectInfoBOS);
        pageResult.setRecords(count);
        return pageResult;

    }

    @Override
    public SubjectInfoBO querySubjectInfo(SubjectInfoBO subjectInfoBO) {
        SubjectInfo subjectInfo = subjectInfoService.queryById(subjectInfoBO.getId());
        if (subjectInfo == null) {
            return null;
        }
        Integer subjectType = subjectInfo.getSubjectType();
        SubjectOptionBO optionBO = subjectTypeHandlerFactory.getHandler(subjectType).query(subjectInfo.getId());
//        SubjectInfoBO result = subjectTypeHandlerFactory.getHandler(subjectType).queryAll(subjectInfo.getId());
        SubjectInfoBO bo = SubjectInfoConvert.INSTANCE.convertOptionAndInfoToBo(optionBO, subjectInfo);
        List<String> labelNameList = new ArrayList<>();
        SubjectMapping subjectMapping = new SubjectMapping();
        subjectMapping.setSubjectId(subjectInfoBO.getId());
        subjectMapping.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        //获取标签信息
        List<SubjectMapping> mappings = subjectMappingService.queryLabelByCategoryId(subjectMapping);
        List<Long> labelIds = mappings.stream().map(SubjectMapping::getLabelId).toList();
        List<SubjectLabel> labelList = subjectLabelService.batchQueryById(labelIds);
        labelList.stream().map(SubjectLabel::getLabelName).forEach(labelNameList::add);
        bo.setLabelName(labelNameList);
        bo.setLiked(subjectLikedDomainService.getLikedStatus(subjectInfoBO.getId(), LoginUtil.getLoginId()));
        bo.setLikedCount(subjectLikedDomainService.getLikedCount(subjectInfoBO.getId()));
        assembleSubjectCursor(subjectInfoBO, bo);
        return bo;
    }

    private void assembleSubjectCursor(SubjectInfoBO subjectInfoBO, SubjectInfoBO bo) {
        Long categoryId = subjectInfoBO.getCategoryId();
        Long labelId = subjectInfoBO.getLabelId();
        Long subjectId = subjectInfoBO.getId();
        if (Objects.isNull(categoryId) || Objects.isNull(labelId)) {
            return;
        }
        Long netSubjectId = subjectInfoService.querySubjectIdCursor(categoryId, labelId, subjectId,1);
        bo.setNextSubjectId(netSubjectId);
        Long preSubjectId = subjectInfoService.querySubjectIdCursor(categoryId, labelId, subjectId,0);
        bo.setLastSubjectId(preSubjectId);
    }

    @Override
    public PageResult<SubjectInfoEs> getSubjectPageBySearch(SubjectInfoBO subjectInfoBO) {
        SubjectInfoEs subjectInfoEs = SubjectInfoConvert.INSTANCE.convertToEsEntity(subjectInfoBO);
        subjectInfoEs.setKeyword(subjectInfoBO.getKeyWord());
        subjectInfoEs.setPageNo(subjectInfoBO.getPageNo());
        subjectInfoEs.setPageSize(subjectInfoBO.getPageSize());
        return subjectEsService.querySubjectList(subjectInfoEs);
    }

    @Override
    public List<SubjectInfoBO> getContributeList() {
        //使用redis zset存储贡献榜
        Set<ZSetOperations.TypedTuple<String>> rankWithScore = redisUtil.rankWithScore(RANK_KEY, 0, 5);
        if (log.isInfoEnabled()) {
            log.info("SubjectInfoDomainServiceImpl.getContributeList.rankWithScore:{}", rankWithScore);
        }
        if (CollectionUtils.isEmpty(rankWithScore)) {
            return Collections.emptyList();
        }
        List<SubjectInfoBO> subjectInfoBOS = new LinkedList<>();
        rankWithScore.forEach(rank -> {
            SubjectInfoBO subjectInfoBO = new SubjectInfoBO();
            subjectInfoBO.setSubjectCount(Objects.requireNonNull(rank.getScore()).intValue());
            UserInfo userInfo = userRpc.getUserInfo(rank.getValue());
            subjectInfoBO.setCreateUser(userInfo.getNickName());
            subjectInfoBO.setCreateUserAvatar(userInfo.getAvatar());
            subjectInfoBOS.add(subjectInfoBO);
        });
        return subjectInfoBOS;
        //数据库查询贡献榜
//        List<SubjectInfo> subjectInfoList = subjectInfoService.getCongtributeCount();
//        if (CollectionUtils.isEmpty(subjectInfoList)) {
//            return Collections.emptyList();
//        }
//        List<SubjectInfoBO> subjectInfoBOS = new LinkedList<>();
//        subjectInfoList.forEach(subjectInfo -> {
//            SubjectInfoBO subjectInfoBO=new SubjectInfoBO();
//            subjectInfoBO.setSubjectCount(subjectInfo.getSubjectCount());
//            UserInfo userInfo = userRpc.getUserInfo(subjectInfo.getCreatedBy());
//            subjectInfoBO.setCreateUser(userInfo.getNickName());
//            subjectInfoBO.setCreateUserAvatar(userInfo.getAvatar());
//            subjectInfoBOS.add(subjectInfoBO);
//        });
//        return subjectInfoBOS;
    }
}
